package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sql.ProjectsDao;
import beans.ProjectItemBean;
import beans.TeamMemberItemBean;

/**
 * Servlet implementation class SetCurrentProject
 */
@WebServlet("/SetCurrentProject")
public class SetCurrentProject extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SetCurrentProject() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		TeamMemberItemBean currentUserInfo = (TeamMemberItemBean) session.getAttribute("currentUser");

		// set session project id
		String projectIdAsString = request.getParameter("projectId");
		int projectId = Integer.parseInt(projectIdAsString);
		currentUserInfo.setProjectId(projectId);
		
		// set session project name
		ProjectsDao projectsDao = new ProjectsDao();
		
		try {
			ProjectItemBean projectItemBean = projectsDao.getProjectData(projectId);
			currentUserInfo.setProjectId(projectItemBean.getId());
			currentUserInfo.setProjectName(projectItemBean.getName());
			session.setAttribute("currentUser", currentUserInfo);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		PrintWriter out = response.getWriter();
		out.write(currentUserInfo.getJson());
	}

}
